package engine.scene
{
	import engine.GameData;
	import engine.control.MenuList;
	import engine.data.ModelLocator;
	import engine.flag.GameDefine;
	import engine.guide.GuideEvent;
	import engine.logic.walk.Astar.ForbiddenAreaLogic;
	import engine.logic.walk.ISceneModel;
	import engine.logic.walk.WalkLogic;
	import engine.logic.walk.WalkManager;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.newUi.DuplicatesLogic;
	import engine.newUi.NpcTalkUI;
	import engine.newUi.SitCrossleggedLogic;
	import engine.scene.player.BasePlayerModel;
	import engine.tip.TipsMainLogic;
	import engine.ui.MainUIManager;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.ui.Mouse;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	
	import newx.StageInfo;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.loader.SwfLoader;
	
	public class SceneView extends Sprite implements ISceneModel
	{
		private var _sceneBG			:Bitmap;
		
		private var _playerBG			:Sprite;
		
		private var _guide				:Sprite;
		
		private var _model				:ModelLocator;
		
		private var _walkManager		:WalkManager;
		
		private var _walkIcon			:MovieClip;
		
		private var _directionIcon		:MovieClip;
		
		//多久时间显示按住的图标（帧为单位）
		private var _dirctionTime		:int	=	5;
		
		//场景移动时间
		private var _sceneTime			:int = 5;
		
		private var _view				:Sprite;
		private var _sceneBitMap 		:Bitmap;
		
		private var _sceneClickLogic	:SceneClickLogic;
		
		private var _scenePlayerLogic	:ScenePlayerLogic;
		
		private var _backSceneView		:BackSceneView;
		
		private var _forntSceneView	:Sprite;
		private var _moveBitMap		:Bitmap;
		private var _isShowIcon:Boolean=false;
		public function SceneView()
		{
			_sceneClickLogic	=	new SceneClickLogic();
			
			_scenePlayerLogic	=	new ScenePlayerLogic();
			
//			_backSceneView		=	new BackSceneView( this );
			
			init();
		}
	
		public function get sceneBG():Bitmap
		{
			return _sceneBG;
		}

		public function get walkIcon():MovieClip
		{
			return _walkIcon;
		}

		public function get view():Sprite
		{
			return _view;
		}

		public function get guide():Sprite
		{
			return _guide;
		}


		private function init():void
		{
			_view				=	new Sprite();
			
			_sceneBitMap		=	new Bitmap();
			_moveBitMap			=   new Bitmap();
			_view.addChild( _sceneBitMap );
			_model				=	ModelLocator.getInstance();
			
			_walkManager		=	WalkManager.getInstance();
			
			_walkIcon			=	ResManager.newResClass("ClickIcon") as MovieClip;
			_walkIcon.name		=	"ClickIcon";
			_walkIcon.mouseChildren = _walkIcon.mouseEnabled = false;
			_walkIcon.stop();
			
			_directionIcon		=	ResManager.newResClass("walkAngle") as MovieClip;
			_directionIcon.mouseChildren = _directionIcon.mouseEnabled = false;
			
			_sceneTime			=	int(StaticIni.getIniVar("SceneSpeed", "time"));
			
			_playerBG 			=	new Sprite();
			
			_guide				=   new Sprite();
			_forntSceneView		=	new Sprite();
			_forntSceneView.mouseChildren = _forntSceneView.mouseEnabled = false;
			
			addEventListener(MouseEvent.MOUSE_DOWN	,onDown);
//			this.addChild( _backSceneView );
			
			this.addChild( _sceneBitMap );
			
			_playerBG 	=	new Sprite();
			this.addChild(_playerBG);
			_guide = new Sprite();
			
			this.addChild( _forntSceneView );
			this.addChild(_guide);
		}
	
		/**
		 *	设置场景位置 
		 * 
		 */
		public function changeSize():void
		{
			//场景宽度
			var viewWidth : int = SceneChangeManager.getGameWidth();
			
			//x偏移坐标
			var dis:Number = ( StageInfo.rootW - viewWidth )  >> 1;
			
			if( x > dis)
			{
				x = dis;
			}
			else
			{
				if( viewWidth < StageInfo.rootMaxW )
				{
					if( x + StageInfo.rootMaxW < viewWidth )
					{//左越界
						x =  ( StageInfo.rootW - viewWidth ) >> 1;
					}
				}
				else
				{//右越界
					x =  ( StageInfo.rootW - StageInfo.rootMaxW ) >> 1;
				}
			}
		}
		
		public function showScene( ):void
		{
			StageInfo.uiSpace.visible		=	true;
			
			var loadCount : int = 0;
			
			if( null != _sceneBitMap.bitmapData )
			{
				_sceneBitMap.bitmapData.dispose();
			}
			_sceneBitMap.bitmapData	= new BitmapData( 2500, 750, true, 0 );
			
			var sceneModel : int = GameData.SceneModel;
			
			if( sceneModel  == -1 ) return;
			
			var isNewScene : int = StaticIni.getIniObj( "Scene_IsNewSceneLoading" )[ sceneModel ];
			
			for( var i : int = 1; i <= 25; i++ )
			{
				var url:String = "res/scenes/" + "mscene_" + sceneModel + "_" + i + ".swf";
				if( 1 == isNewScene  )
				{
//					ResManager.poorLoadRes(url,url,onComplete,[i, isNewScene]);
					SwfLoader.StartLoad( url, null,onComplete,[i, isNewScene,url] );
				}else
				{
					url = "res/scenes/" + "scene_" + sceneModel + "_" + i + ".swf"
//					ResManager.poorLoadRes(url,url,onComplete,[i, isNewScene]);
					SwfLoader.StartLoad( url, null,onComplete,[i, isNewScene,url] );
				}
			}
			
			
			function onComplete( swf : MovieClip, pList : Array ):void
			{
				if(swf	==	null)
				{
					SwfLoader.StartLoad( pList[2], null,onComplete,pList );
					return;
				}
				var scenePieceWidth:int	=	100;
				if(GameData.SceneType==GameDefine.SceneType_ForbiddenAreaScene) scenePieceWidth	=	52;//1300/25
				bmd = new BitmapData(scenePieceWidth,750,true,0);
				bmd.draw( swf );
				_sceneBitMap.bitmapData.copyPixels( bmd, bmd.rect, new Point(  ( pList[0] - 1 ) * scenePieceWidth, 0 ) );
//				_sceneBitMap.alpha =0;
				loadCount ++;
				
//				if( 25 == loadCount && pList[ 1 ] == 1)
//				{
//					_backSceneView.showScene();
//				}
			}
			
			//根据场景坐标，看加载什么地图
			var bmd : BitmapData ;
			if( isNewScene == 1 )
			{
				var furl:String = "res/scenes/" + "fscene_" + sceneModel + ".swf";
				//加载前景
//				ResManager.poorLoadRes(furl,furl,onComplete1);
				SwfLoader.StartLoad( furl, null,onComplete1 );
				
				function onComplete1( swf : MovieClip, pList : Array ):void
				{
					if( null == swf )
					{
						return;
					}
					_forntSceneView.addChild( swf );
				}
			}
		}
		
		/**
		 * 设置场景背景 
		 * @param val
		 * 
		 */		
		public function setSceneBG(val:MovieClip):void
		{
			if( null != this )
			{
				//清空玩家
				_scenePlayerLogic.clear();
				
//				if( null != this.parent )
//				{
//					this.parent.removeChild( this );
//				}
				
				while( _forntSceneView.numChildren )
				{
					_forntSceneView.removeChildAt( 0 );
				}
				
//				this.removeChild( _playerBG );
//				
//				this.removeChild(_guide);
				
//				_guide = null;
				if(_sceneBG)
				{
					if(_sceneBG.parent)
						removeChild(_sceneBG);					
				}
				_sceneBG = null;
				
//				_backSceneView.leave();
			}
//			_sceneBG = new Bitmap();
			_sceneBitMap.bitmapData	= new BitmapData( val.width, val.height , true, 0 );	
			_sceneBitMap.bitmapData.draw(val);
//			if(GameData.SceneType==GameDefine.SceneType_ForbiddenAreaScene)
//			{
//				_sceneBG.visible = false;
//			}else
//			{
//				_sceneBG.visible = true;
//				addChildAt(_sceneBG,0);
//			}
			
		
//			this.addChild( _backSceneView );
//			
//			this.addChild( _view );
//			
//			_playerBG 	=	new Sprite();
//			this.addChild(_playerBG);
//			_guide = new Sprite();
//			
//			this.addChild( _forntSceneView );
//			this.addChild(_guide);
			_playerBG.mouseEnabled = false;
			
			this.y	=	SceneChangeManager.topOffsize;
			
			_model.dispatchEvent(new GuideEvent( GuideEvent.SWITCH_SCENE, [ GameData.SceneConfig ] ) );
		}
		
		/**
		 * 移动的x，y坐标距离
		 * @param x
		 * @param y
		 */
		public function moveFollow(xDistance : int, direction : int):void
		{
			if(StageInfo.stage.stageWidth > 2500) return;
			
			var viewWidth : int = SceneChangeManager.getGameWidth();
			var fw:Number = viewWidth - 2500 + 
				(StageInfo.rootW - viewWidth ) * .5;
			if(x >= (StageInfo.rootW - viewWidth) * .5 && xDistance <= 0)
			{
				return;
			}
			else if(x <= fw && xDistance >= 0)
			{
				return
			}
			
			var xPoint : int = x;
			var dis : int = viewWidth - 200;
			if(xDistance < 0 && direction != 2)
			{
				xPoint = Math.min((x + dis), (StageInfo.rootW - viewWidth) * .5);
			}
			else if(xDistance > 0 && direction != 1)
			{
				xPoint = Math.max((x - dis), fw);
			}
			
			
			if(x != xPoint)
			{
				x = xPoint - int ( xDistance < 0 ) * 200;
			}
		}
		
		public function move(xDistance : int, yDistance : int):void
		{
			
			var viewWidth : int = SceneChangeManager.getGameWidth();
			var fw:Number = viewWidth - 2500 + 
				(StageInfo.rootW - viewWidth ) * .5;
			if(x >= (StageInfo.rootW - viewWidth) * .5 + xDistance && xDistance < 0)
			{
				return;
			}
			else if(x <= fw + xDistance && xDistance > 0)
			{
				return
			}
			x -= xDistance;	
//			_backSceneView.move( xDistance, yDistance ); 
		}
		
		public function get playerBG():Sprite
		{
			return _playerBG;
		}
		
		private function onDown(e:MouseEvent):void
		{
			if(WalkLogic.Fight) return;
			if( this == null ) return;
			if( e.target as Sprite == null ) return;
			if( ! contains( e.target as Sprite ) )
			{
				return
			}
			MainUIManager.getInstance().autoFoundWay	=	false;
			DuplicatesLogic.getInstance().FBSceneID("","");
			SitCrossleggedLogic.getInstance().onClickStage();
			
			MenuList.hide();
			TipsMainLogic.instance.hide();
			
//			var role : BasePlayerModel = _scenePlayerLogic.role;
//			
//			if( null == role )
//			{//主角没有加载完
//				return;
//			}
			
			_dirctionTime = 0;
			
			var clickPoint : Point = new Point( mouseX, mouseY  );
			
			StageInfo.stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
			
			if(GameData.SceneType	==	GameDefine.SceneType_ForbiddenAreaScene)//SceneType_Normal;SceneType_ForbiddenAreaScene
			{
				return;
			}
			
			if( _sceneClickLogic.playerMove( GameData.Role, clickPoint, walkOver) )
			{//是否可以行走
				showWalkIcon( clickPoint );
				if(NpcTalkUI.getInstance().stage) NpcTalkUI.getInstance().hideCur();
			}
			
			WalkManager.getInstance().walkLogic.addWalkFunc(onMove)
//			StageInfo.stage.addEventListener(Event.ENTER_FRAME, onMove);
		}
		
		private function onUp(e:MouseEvent):void
		{
			_dirctionTime = 0;
			
			StageInfo.stage.removeEventListener(MouseEvent.MOUSE_UP,onUp);
			
			if(GameData.SceneType	==	GameDefine.SceneType_ForbiddenAreaScene) return;//SceneType_Normal;SceneType_ForbiddenAreaScene

			WalkManager.getInstance().walkLogic.delWalkFunc(onMove);
//			StageInfo.stage.removeEventListener(Event.ENTER_FRAME, onMove);
			
			var roleModel : BasePlayerModel = GameData.Role;
			
			if( _directionIcon.parent )
			{//当时按着鼠标的移动时
				stopWalk( roleModel );
			}
		}
		
		private function onMove():void
		{
			if( _dirctionTime < 5 ) 
			{//说明还没到显示的时间
				_dirctionTime++;
				return;
			}
			
			var clickPoint : Point = new Point( mouseX, mouseY );
			
			showAllWalkIcon( GameData.Role, clickPoint );
			
			if( _directionIcon.parent )
			{
				_sceneClickLogic.playerMove( GameData.Role, clickPoint, walkOver );
			}
		}
		
		private function stopWalk( role : BasePlayerModel ):void
		{
			//告诉服务端我走了
			SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMSG_PLAYER_MOVETO, role.point.x, role.point.y, int( role.point.x ), int( role.point.y ) );
			
			//自己在走
			_walkManager.roleMove( role, new Point( role.point.x, role.point.y ), role.point, walkOver );
			
			hideAllWalkIcon();
		}
		
		public function showWalkIcon(val:Point):void
		{
			if( !_walkIcon.parent )
			{
				this.addChild(_walkIcon);
	
				hideAllWalkIcon();
			}
			
			(_walkIcon.getChildAt(0) as MovieClip).gotoAndPlay(1);
			
			_walkIcon.y		=	val.y;
			_walkIcon.x 	=	val.x;	
		}
		private function showAllWalkIcon( role : BasePlayerModel, p : Point ):void
		{
			Mouse.hide();
			
			if( null == _directionIcon.parent )
			{
				this.addChild( _directionIcon );
				_directionIcon.play();
				
				hideWalkIocn();
			}
			_isShowIcon=true;
			_directionIcon.x 		=	p.x;
			_directionIcon.y		=	p.y;
			
			var angle:Number	=	Math.atan2( p.y - role.y , p.x - role.x);
			if(0 != angle)
			{
				_directionIcon.rotation	=	angle * 180 / Math.PI
			}
		}
		
		private function hideAllWalkIcon():void
		{
			Mouse.show();
			_isShowIcon=false;
			if( _directionIcon.parent )
			{
				_directionIcon.parent.removeChild( _directionIcon );
			}
		}
		public function hideWalkIocn():void
		{
			_walkIcon.stop();
			
			if(_walkIcon.parent)
			{
				_walkIcon.parent.removeChild(_walkIcon);
			}
		}
		public function get haveWalkIocn():Boolean
		{
			return _isShowIcon;
		}
		
		public function walkOver():void
		{
			hideWalkIocn();
		}

		public function get scenePlayerLogic():ScenePlayerLogic
		{
			return _scenePlayerLogic;
		}
//
//		public function get backSceneView():BackSceneView
//		{
//			return _backSceneView;
//		}

		public function get sceneBitMap():Bitmap
		{
			return _sceneBitMap;
		}
	}
}